/**
 * Created by lizhe on 2018/4/17.
 */
var x = 0;
var datas = [];
var zTree;
var setting = {
    callback: {
        onClick: zTreeOnClick
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};
var zNodes =[];
var ZtreeId = 0;
var ZtreeName = "";
var type =["","文章","图片","教师","学生","基本概况","教师风采"];

var croppable = false;
$(document).ready(function(){
    var $image = $('#image');
    $image.cropper({
        aspectRatio: 860/439,
        viewMode: 1,
        ready: function () {
            croppable = true;
        }
    });

    $("#AddBanner").click(function(){
        var imgId = "img-"+x;
        var imgInputId = "imgInput-"+x;
        var id = 'id-'+x;
        var urlId = 'url-'+x;
        var sortId = 'sort-'+x;
        var imgurlId = "imgurl-"+x;
        document.getElementById("content").innerHTML = document.getElementById("content").innerHTML +
            '<div class="divContent">'+
            '<div class="divList">'+
            '<span id='+imgurlId+' class="hidden">images/bannerAdd.png</span>'+
            '<img src="images/bannerAdd.png" class="img" id="'+imgId+'" onclick=imageClick("'+imgInputId+'")>'+
            '<input type="file" class="hidden" id="'+imgInputId+'" onchange=changeimage(this,"image")>'+
            '<span class="hidden" id="'+id+'"></span>'+
            '</div>'+
            '<div style="margin-top: 10px">'+
            '<div class="col-sm-2 control-label" style="padding-top: 4px">链接</div>'+
            '<div class="col-sm-10">'+
            '<input type="text" placeholder="链接" class="inputText" value="" id="'+urlId+'">'+
            '</div>'+
            '</div>'+
            '<div style="margin-top: 50px">'+
            '<div class="col-sm-2 control-label" style="padding-top: 4px">排序</div>'+
            '<div class="col-sm-10">'+
            '<input type="number" value="0" class="inputText" id="'+sortId+'">'+
            '</div>'+
            '</div>'+
            '<div>'+
            '<div class="col-md-12">'+
            '<a class="btn btn-primary button" style="width: 306px" onclick="selectUrl(this,'+x+')">'+
            '<i class="fa fa-pencil-square-o"></i>'+
            '&nbsp;选择链接'+
            '</a>'+
            '</div>'+
            '<div class="col-sm-5">'+
            '<a class="btn btn-primary button" onclick="saveBanner(this,'+x+')">'+
            '<i class="fa fa-trash-o"></i>'+
            '&nbsp;保存'+
            '</a>'+
            '</div>'+
            '<div class="col-sm-5">'+
            '<a class="btn btn-danger button" onclick="DeleteBanner(this,'+x+')" style="margin-left: 35px">'+
            '<i class="fa fa-trash-o"></i>'+
            '&nbsp;删除'+
            '</a>'+
            '</div>'+
            '<div class="col-sm-2 control-label"></div>'+
            '</div>'+
            '</div>'
    });

    //确认删除
    $("#del_confirm").click(function(){
        var id = document.getElementById("del_id").innerHTML;
        $.ajax({
            url : urladdr + "/web/banner/delete",
            method : "POST",
            data : {
                token:Mytoken,
                id:id
            },
            success : function(data){
                if(data.code == 0){
                    modalinfo("删除成功");
                    modalclose("#deletemodal");
                    queryBanner();
                }else if(data.code == 401){
                    location.href = "index.html"
                }else{
                    modalinfo(data.msg);
                }
            }
        });
    });

    //选择URL——确定
    $("#column_confirm").click(function(){
        var t = document.getElementById("article_table");
        var urltotal = articleAddr + "/modules/website/";
        var url = "";
        var j = document.getElementById("list_i").innerHTML;
        var next = "0";
        for(var i=0;i< t.rows.length;i++) {
            if (t.rows[i].style.background == "rgb(223, 240, 216)" || t.rows[i].style.background == "rgb(223, 240, 216) none repeat scroll 0% 0%") {
                var type = t.rows[i].cells[6].innerHTML;
                var menuId = t.rows[i].cells[7].innerHTML;
                var id = t.rows[i].cells[0].innerHTML;
                if(type == "1" || type == "5"){
                    var html = "text.html";
                }else if(type == "2"){
                    html = "text.html";
                }else if(type == "3" || type == "6"){
                    html = "teacherText.html";
                }else if(type == "4"){
                    html = "student.html";
                }
                for(var k = 0;k<datas.length;k++){
                    if(datas[k].id == menuId){
                        break;
                    }
                }
                if(datas[k].height !=0){
                    for(var z=0;z<datas.length;z++){
                        if(datas[k].parentId == datas[z].id){
                            next = "1";
                            break;
                        }
                    }
                }

                url = urltotal + html + "?menuId="+menuId + "&id="+ id+"&next="+next;
                document.getElementById("url-"+j).value = url;
                modalclose("#Urlmodal");
                break;
            }
        }
    });

    document.getElementById("bannerTime").value = bannertime;

    $("#bannerSave").click(function(){
        $.ajax({
            url : urladdr + "/website/bannerTime",
            method : "GET",
            data : {
                token:Mytoken,
                time:document.getElementById("bannerTime").value
            },
            success : function(data){
                if(data.code == 0){
                    modalinfo("修改成功");
                }else if(data.code == 401){
                    location.href = "index.html"
                }else{
                    modalinfo(data.msg);
                }
            }
        });
    });

    queryBanner();
});

//ztree回调
function zTreeOnClick(event, treeId, treeNode) {
    var id = treeNode.id;
    var name = treeNode.name;
    var tId = treeNode.tId;
    ZtreeId = id;
    ZtreeName = name;
    queryArticle(1,10,id,0);
}

function queryBanner(){
    $.ajax({
        url : urladdr + "/web/banner/list",
        method : "GET",
        data : {
            token:Mytoken
        },
        success : function(data){
            if(data.code == 0){
                $("#content").empty();
                $.each(data.data,function(i,date){
                    x = i+1;
                    var imgId = "img-"+i;
                    var imgInputId = "imgInput-"+i;
                    var id = 'id-'+i;
                    var urlId = 'url-'+i;
                    var sortId = 'sort-'+i;
                    var imgurlId = "imgurl-"+i;
                    var image = imgUrl + date.imageUrl;
                    document.getElementById("content").innerHTML = document.getElementById("content").innerHTML +
                        '<div class="divContent">'+
                        '<div class="divList">'+
                        '<span id='+imgurlId+' class="hidden">'+date.imageUrl+'</span>'+
                        '<img src="'+image+'" class="img" id="'+imgId+'" onclick=imageClick("'+imgInputId+'")>'+
                        '<input type="file" class="hidden" id="'+imgInputId+'" onchange=changeimage(this,"image")>'+
                        '<span class="hidden" id="'+id+'">'+date.id+'</span>'+
                        '</div>'+
                        '<div style="margin-top: 10px">'+
                        '<div class="col-sm-2 control-label" style="padding-top: 4px">链接</div>'+
                        '<div class="col-sm-10">'+
                        '<input type="text" placeholder="链接" class="inputText" value="'+date.bannerUrl+'" id="'+urlId+'">'+
                        '</div>'+
                        '</div>'+
                        '<div style="margin-top: 50px">'+
                        '<div class="col-sm-2 control-label" style="padding-top: 4px">排序</div>'+
                        '<div class="col-sm-10">'+
                        '<input type="number" value="'+date.priority+'" class="inputText" id="'+sortId+'">'+
                        '</div>'+
                        '</div>'+
                        '<div>'+
                        '<div class="col-md-12">'+
                        '<a class="btn btn-primary button" style="width: 306px" onclick="selectUrl(this,'+i+')">'+
                        '<i class="fa fa-pencil-square-o"></i>'+
                        '&nbsp;选择链接'+
                        '</a>'+
                        '</div>'+
                        '<div class="col-sm-5">'+
                        '<a class="btn btn-primary button" onclick="saveBanner(this,'+i+')">'+
                        '<i class="fa fa-trash-o"></i>'+
                        '&nbsp;保存'+
                        '</a>'+
                        '</div>'+
                        '<div class="col-sm-5">'+
                        '<a class="btn btn-danger button" onclick="DeleteBanner(this,'+i+')" style="margin-left: 35px">'+
                        '<i class="fa fa-trash-o"></i>'+
                        '&nbsp;删除'+
                        '</a>'+
                        '</div>'+
                        '<div class="col-sm-2 control-label"></div>'+
                        '</div>'+
                        '</div>'
                });
            }else if(data.code == 401){
                location.href = "index.html"
            }else{
                modalinfo(data.msg);
            }
        }
    });
}

function selectUrl(obj,i){
    var content = document.getElementById("content").getElementsByClassName("divContent");
    showmodal("#Urlmodal");
    selectTree();
    document.getElementById("list_i").innerHTML = i;
    ZtreeId = 0;
    ZtreeName = "";
    //queryArticle(1,10,0,2);
}

function saveBanner(obj,i){
    var content = document.getElementById("content").getElementsByClassName("divContent");
    var imgId = "img-"+i;
    var imgInputId = "imgInput-"+i;
    var id = 'id-'+i;
    var urlId = 'url-'+i;
    var sortId = 'sort-'+i;
    var imgurlId = "imgurl-"+i;

    var bannerId = document.getElementById(id).innerHTML;
    var imageUrl = document.getElementById(imgurlId).innerHTML;
    var bannerUrl = document.getElementById(urlId).value;
    var priority = document.getElementById(sortId).value;
    if(imageUrl=="images/bannerAdd.png"){
        modalinfo("请上传图片");
    }else if(bannerUrl == ""){
        modalinfo("请输入链接");
    }else if(priority == ""){
        modalinfo("请输入排序");
    }else{
        if(bannerId == ""){
            var data={
                imageUrl:imageUrl,
                bannerUrl:bannerUrl,
                priority:priority
            };
            $.ajax({
                url : urladdr + "/web/banner/add?token="+Mytoken,
                method : "POST",
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify(data),
                success : function(data){
                    if(data.code == 0){
                        modalinfo("保存成功");
                        queryBanner();
                    }else if(data.code == 401){
                        location.href = "index.html"
                    }else{
                        modalinfo(data.msg);
                    }
                }
            });
        }else{
            data={
                id:bannerId,
                imageUrl:imageUrl,
                bannerUrl:bannerUrl,
                priority:priority
            };
            $.ajax({
                url : urladdr + "/web/banner/update?token="+Mytoken,
                method : "POST",
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify(data),
                success : function(data){
                    if(data.code == 0){
                        modalinfo("保存成功");
                        queryBanner();
                    }else if(data.code == 401){
                        location.href = "index.html"
                    }else{
                        modalinfo(data.msg);
                    }
                }
            });
        }
    }
}

function DeleteBanner(obj,i){
    var content = document.getElementById("content").getElementsByClassName("divContent");
    var id = 'id-'+i;
    var bannerId = document.getElementById(id).innerHTML;
    showmodal("#deletemodal");
    document.getElementById("del_id").innerHTML = bannerId;
}

function selectTree(){
    $.ajax({
        url : urladdr + "/web/menu/list",
        method : "GET",
        data : {
            token:Mytoken
        },
        success : function(data){
            if(data.code == 0){
                zNodes.splice(0,zNodes.length);
                datas.splice(0,datas.length);
                $.each(data.data,function(i,date){
                    var d ={
                        id:date.id,name:date.title,parentId:date.parentId,height:date.height,type:date.type
                    };
                    datas.push(d);
                });

                $.each(data.data,function(i,date){
                    if(date.height == 0){
                        var d={
                            id:date.id, pId:date.parentId, name:date.title+"("+type[date.type]+")", open:true, iconSkin:"pIcon01"
                        };
                    }else if(date.height == 1){
                        d={
                            id:date.id, pId:date.parentId, name:date.title+"("+type[date.type]+")", open:true, iconSkin:"icon01"
                        };
                    }else if(date.height == 2){
                        d={
                            id:date.id, pId:date.parentId, name:date.title+"("+type[date.type]+")", iconSkin:"icon03"
                        };
                    }
                    zNodes.push(d);
                });
                setTimeout(function(){
                    $.fn.zTree.init($("#selectTree"), setting, zNodes);
                },100)
            }else if(data.code == 401){
                location.href = "index.html"
            }else{
                modalinfo(data.msg);
            }
        }
    });
}

function queryArticle(page,pageSize,menuId,status){
    $.ajax({
        url : urladdr + "/web/article/list",
        method : "GET",
        data : {
            token:Mytoken,
            page:page,
            pageSize:pageSize,
            menuId:menuId,
            status:status
        },
        success : function(data){
            if(data.code == 0){
                $("#article_table").empty();
                $.each(data.data.list,function(i,date){
                    document.getElementById("article_table").innerHTML = document.getElementById("article_table").innerHTML +
                        '<tr>'+
                        '<td class="hidden">'+date.id+'</td>' +
                        '<td>'+date.title+'</td>' +
                        '<td>'+date.userName+'</td>'+
                        '<td class="hidden">'+date.imageUrl+'</td>'+
                        '<td class="hidden">'+date.content+'</td>'+
                        '<td class="hidden">'+date.ext+'</td>'+
                        '<td class="hidden">'+date.type+'</td>'+
                        '<td class="hidden">'+date.menuId+'</td>'+
                        '</tr>'
                });
                $("#page").pagination({
                    pages: data.data.pageCount,
                    cssStyle: 'light-theme',
                    displayedPages:5,
                    edges:2,
                    currentPage:page
                });
                document.getElementById("recordCount").innerHTML = data.data.totalCount;
                document.getElementById("pageCount").innerHTML = data.data.totalPage;
                clicktable('article_table');
            }else if(data.code == 401){
                location.href = "index.html"
            }else{
                modalinfo(data.msg);
            }
        }
    });
}

function uplodbase64() {
    var $image = $('#image');
    var $result = $('#result');

    var croppedCanvas;
    var roundedCanvas;

    if (!croppable) {
        return;
    }
    // Crop
    croppedCanvas = $image.cropper('getCroppedCanvas');
    // Round
    roundedCanvas = getRoundedCanvas(croppedCanvas);

    // Show
    $result.html('<img src="' + croppedCanvas.toDataURL() + '">');
    var x = croppedCanvas.toDataURL();
    modalclose("#imagemodal");
    showmodal("#progressmodal");
    setTimeout(function () {
        var base64 = x;
        base64 = base64.split(",");
        var imageData = new FormData();
        imageData.append('base64', base64[1]);
        imageData.append('token', Mytoken);
        $.ajax({
            url: urladdr+"/web/uploadBase64Image?token="+Mytoken,
            method: "POST",
            data: imageData,
            processData: false,
            contentType: false,
            ////这里我们先拿到jQuery产生的 XMLHttpRequest对象，为其增加 progress 事件绑定，然后再返回交给ajax使用
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                if (onprogress && xhr.upload) {
                    xhr.upload.addEventListener("progress", onprogress, false);
                    return xhr;
                }
            },
            success: function (data) {
                if (data.code == 0) {
                    var imageUrl = data.data;
                    var id = document.getElementById("imgId").innerHTML;
                    var imgId = "img-"+id;
                    var imgurlId = "imgurl-"+id;
                    document.getElementById(imgId).src = imgUrl+imageUrl;
                    document.getElementById(imgurlId).innerHTML = imageUrl;
                    setTimeout(function(){
                        modalclose("#progressmodal");
                    },500)
                }else{
                    modalclose("#imagemodal");
                    modalinfo(data.msg);
                }
            }
        })
    }, 500);
}


